<template>
	<view class="y-upload">
		<view class="item" v-for="(i, key) in list" :key="i._key">
			<view class="formicon form-guanbi1" @click="del(key)" v-if="!keys.disabled"></view>
			<view class="wave-progress" v-if="!i.ok">
				<view class="inner">
					<view class="water" :style="{ top: 100 - i.progress + '%' }"></view>
					<view class="tips">{{ i.progress }}</view>
				</view>
			</view>
			<view v-if="icon[i.path]" class="icon fileicon" :class="i.icon" @click="preImage(i)"></view>
			<image v-else @error="setIcon(i.path, true)" @load="setIcon(i.path, false)" class="img" :src="src + i.path" @click="preImage(i)"></image>
		</view>
		<view ref="input" class="item fileicon add iconshangchuan" v-if="!keys.disabled"><view class="formicon form-jia"></view></view>
	</view>
</template>
<script>
import { isiOS } from '@/a/utils/api.js';
export default {
	name: 'yUpload',
	props: {
		keys: {
			type: Object,
			default() {
				return {};
			}
		},
		value: {
			type: [String, Array],
			default() {
				return [];
			}
		}
	},
	data() {
		return {
			uploadList: [],
			icon: {},
			src: '',
			fileIcon: {
				'.MP4': 'icontubiaoku-',
				'.AVI': 'icontubiaoku-',
				'.WMV': 'icontubiaoku-',
				'.3GP': 'icontubiaoku-',
				'.MKV': 'icontubiaoku-',
				'.FLV': 'icontubiaoku-',
				'.RMVB': 'icontubiaoku-',
				'.BMP': 'iconpicture',
				'.JPEG': 'iconpicture',
				'.SVG': 'iconpicture',
				'.JPG': 'iconpicture',
				'.JP2': 'iconpicture',
				'.GIF': 'iconpicture',
				'.TIFF': 'iconpicture',
				'.PNG': 'iconpicture',
				'.EXIF': 'iconpicture',
				'.WBMP': 'iconpicture',
				'.MBM': 'iconpicture',
				'.WZWJ': 'iconweizhiwenjian',
				'.DOC': 'iconWORD',
				'.DOCX': 'iconWORD',
				'.WPS': 'iconwps',
				'.XLS': 'iconxls',
				'.XLSX': 'iconxls',
				'.PPT': 'iconppt',
				'.PPTX': 'iconppt',
				'.PDF': 'iconpdf',
				'.RAR': 'iconrar',
				'.ZIP': 'iconyasuobao',
				'.7Z': 'icon7Z-icon',
				'.TXT': 'icontxt'
			}
		};
	},
	// uni-app input不支持type=“file”类型所以需要js创建
	mounted() {
		this.addInput();
	},
	computed: {
		list() {
			let data = [];
			try {
				if (Array.isArray(this.value)) {
					data = [
						...this.value.filter(x => {
							const fileType = x.type.toUpperCase();
							x.icon = this.fileIcon['.' + fileType] || 'iconweizhiwenjian';
							return x;
						}),
						...this.uploadList
					];
				} else if (typeof this.value === 'string') {
					data = [
						...this.value
							.split(',')
							.map(x => {
								const fileType = x
									.split('.')
									.pop()
									.toUpperCase();
								return {
									icon: this.fileIcon['.' + fileType] || 'iconweizhiwenjian',
									path: x,
									progress: 100,
									ok: true
								};
							})
							.filter(x => {
								if (x.path) {
									return x;
								}
							}),
						...this.uploadList
					];
				} else {
					data = this.uploadList;
				}
			} catch (e) {}
			return data.filter(x => {
				if (x.path) {
					return x;
				}
			});
		}
	},
	methods: {
		addInput() {
			// 创建附件上传
			const input = document.createElement('input'); //创建元素
			input.setAttribute('type', 'file');
			input.setAttribute('accept', this.keys.accept || '*');
			input.setAttribute('name', 'flie');
			isiOS || this.keys.multiple && input.setAttribute('multiple','multiple');
			Object.assign(input.style, {
				position: 'absolute',
				zIndex: 99,
				top: 0,
				bottom: 0,
				left: 0,
				right: 0,
				width: '100%',
				height: '100%',
				margin: 'auto',
				opacity: 0
			});
			input.addEventListener('change', event => {
				const res = input.files;
				input.remove();
				this.addInput();
				const files = {
					tempFilePaths: [],
					tempFiles: []
				};
				for (let i = 0; i < res.length; i++) {
					const x = res[i];
					const path = (window.URL || window.webkitURL).createObjectURL(x);
					files.tempFilePaths.push(path);
					files.tempFiles.push({
						name: x.name,
						path,
						size: x.size,
						type: x.type
					});
				}
				this.chooseImage(files);
			});
			this.$refs.input.$el.appendChild(input);
		},
		upFile(res, keys) {
			return res.tempFiles.filter(x => {
				//提取格式
				const format = /\.[^\.]+$/
						.exec(x.name)[0]
						.toUpperCase()
						.replace('.', ''),
					arr = keys.format || [];
				let title = '';
				if (parseInt(x.size / 1024 / 1024) > (keys.size || 10)) {
					title = `文件大于${keys.size || 10}MB,不能上传`;
				} else if (arr.map(x => x.toUpperCase()).includes(format)) {
					return x;
				} else if (arr.length) {
					title = `只能上传${arr.join(',')}文件`;
				} else {
					return x;
				}
				uni.showToast({
					icon: 'none',
					title,
					duration: 3000
				});
			});
		},
		chooseImage(res) {
			res = this.upFile(res, this.keys);
			this.uploadList = [
				...this.uploadList,
				...res.map(x => {
					const row = {
						progress: 0,
						path: '',
						ok: false,
						...x,
						path: 'uploading',
						_key: Math.random()
					};
					$http.up[this.keys.upload || ''](
						x.path,
						{},
						e => {
							if (row.progress < 100) {
								row.progress = e.progress;
							}
							if (e.progress == 100) {
								row.progress = '保存中';
							}
						},
						uploadTask => {
							row.uploadTask = uploadTask;
						}
					).then(res => {
						const { path } = res;
						if (path) {
							row.path = path;
							row.ok = true;
							this.change(this.list);
						}
						for (let i = 0; i < this.uploadList.length; i++) {
							if (this.uploadList[i]._key === row._key) {
								this.uploadList.splice(i, 1);
								return;
							}
						}
					});
					return row;
				})
			].filter(x => {
				if (x) return x;
			});
		},
		del(key) {
			const o = this.list[key],
				l = JSON.parse(JSON.stringify(this.list));
			if (o.progress < 100) {
				for (let i = 0; i < this.uploadList.length; i++) {
					if (this.uploadList[i]._key === o._key) {
						try {
							this.uploadList[i].uploadTask.abort();
						} catch (e) {}
						this.uploadList.splice(i, 1);
						return;
					}
				}
			} else {
				l.splice(key, 1);
				this.change(l);
			}
		},
		change(list) {
			const str =
				list
					.map(x => {
						if (x.ok) {
							return x.path;
						}
					})
					.filter(x => {
						if (x) {
							return x;
						}
					})
					.join(',') || '';
			this.$emit('input', str);
		},
		setIcon(key, s) {
			this.$set(this.icon, key + '', s);
		},
		preImage(i) {
			if (!this.icon[i.path]) {
				const current = this.src + i.path;
				uni.previewImage({
					current,
					urls: [current]
				});
			} else {
				window.open('http://preview.t.guizhouguotaijiu.com/onlinePreview?url=' + encodeURIComponent('http://ddscjccf.t.guizhouguotaijiu.com:9527' + this.src + i.path));
			}
		}
	}
};
</script>

<style lang="scss">
@import url('//at.alicdn.com/t/font_1913401_sn588mvkr7c.css');
.y-upload {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	.icon {
		box-sizing: border-box;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #3482f0;
		font-size: 48px;
		border-radius: inherit;
		background-color: rgba(0, 0, 0, 0.05);
		z-index: 11;
	}
	.item {
		width: 30%;
		position: relative;
		margin: 1%;
		border-radius: 6px;
		// overflow: hidden;
		box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.1);

		&::before {
			content: '';
			display: block;
			width: 0;
			height: 0;
			background: red;
			padding-top: 100%;
		}

		.form-guanbi1 {
			font-size: 28px;
			color: #fff;
			position: absolute;
			top: 0;
			right: 0;
			border-radius: 4px;
			line-height: 1em;
			height: 1em;
			width: 1em;
			background: rgba(0, 0, 0, 0.5);
			transform: translateY(-15%) translateX(20%);
			z-index: 12;
		}

		&.add {
			box-sizing: border-box;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #3482f0;
			font-size: 32px;
			border-radius: inherit;
			background-color: rgba(0, 0, 0, 0.05);
			border-radius: 5px;

			.form-jia {
				&::before {
					font-size: 36px;
				}
			}

			&.iconshangchuan {
				color: #a8a8a8;
				border: 1rpx dashed;
				font-size: 30px;
				background: rgba(0, 0, 0, 0);
			}

			&:active {
				box-shadow: 0 0 6px 0 rgba(255, 0, 0, 0.4);

				&::after {
					border-color: red;
				}

				.form-jia {
					text-shadow: 1px 1px 3px rgba(255, 0, 0, 0.4);
				}
			}
		}

		.img {
			position: absolute;
			top: 0;
			right: 0;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 100%;
			border-radius: inherit;
			z-index: 11;
		}
	}
}

@keyframes spin {
	from {
		-webkit-transform: rotate(0deg);
		transform: rotate(0deg);
	}

	to {
		-webkit-transform: rotate(360deg);
		transform: rotate(360deg);
	}
}

.wave-progress {
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	width: 78%;
	height: 78%;
	border-radius: 50%;
	margin: auto;
	border: 2px solid #fd6b65;
	background-color: #f8f8f8;
	box-sizing: border-box;

	.inner {
		position: absolute;
		width: 100%;
		height: 100%;
		border-radius: 50%;
		overflow: hidden;
		border: 2px solid #ffafac;
		box-sizing: border-box;
		z-index: 10;

		.water {
			position: absolute;
			width: 200%;
			height: 200%;
			left: -50%;
			border-radius: 40%;
			background: rgba(255, 175, 172, 0.3);
			-webkit-animation: spin 10s linear infinite;
			animation: spin 10s linear infinite;
		}
	}

	.tips {
		display: flex;
		position: absolute;
		top: 0;
		bottom: 0;
		justify-content: center;
		align-items: center;
		left: 0;
		right: 0;
		color: #ff557f;
		font-size: 12px;
		text-align: center;
	}
}
</style>
